using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Drawing;

namespace LogAnalyzer.Controls
{
    public class ViewerRichTextBox : RichTextBox
    {
        private bool _followMode = false;
        private EventHandler _hndEnter;
        private int _lastRightClickedLineFirstCharIndex = -1;


        public ViewerRichTextBox()
        {
            Font = new Font("Courier New", 8f, FontStyle.Regular);
            ForeColor = Color.LightGray;
            BackColor = Color.Black;
            Dock = DockStyle.Fill;
            ReadOnly = true;
            WordWrap = false;
            ScrollBars = RichTextBoxScrollBars.Both;
            TabStop = false;
            DetectUrls = true;

            _hndEnter = new EventHandler(ViewerRichTextBox_Enter);
        }


        protected override void OnMouseDown(MouseEventArgs e)
        {
            int idx = this.GetCharIndexFromPosition(e.Location);
            //while (true)
            //{
            //    if (idx == this.Text.Length - 1)
            //        break;

            //    idx--;

            //    if (idx == -1)
            //        break;

            //    if (this.Text[idx] == '\n')
            //        break;                
            //}

            //_lastRightClickedLineFirstCharIndex = ++idx;

            _lastRightClickedLineFirstCharIndex = GetFirstCharIndexFromLine(GetLineFromCharIndex(idx));

            base.OnMouseDown(e);
        }

        private void ViewerRichTextBox_Enter(object sender, EventArgs e)
        {
            if (base.Parent != null)
                base.Parent.Focus();
        }



        public bool FollowMode
        {
            get { return _followMode; }
            set 
            {
                bool _oldFollowMode = _followMode;
                _followMode = value;
                if (_followMode)
                {
                    if (_oldFollowMode == false)
                        base.Enter += _hndEnter;

                    ViewerRichTextBox_Enter(this, null);
                }
                else
                {
                    base.Enter -= _hndEnter;
                }
            }
        }

        public int LastRightClickedLineFirstCharIndex
        {
            get { return _lastRightClickedLineFirstCharIndex; }
        }

    }
}
